window.searchProducts = async function () {
    const q = document.getElementById('q').value.trim();
    const resultPanel = document.getElementById('results');
    if (!q) {
        resultPanel.innerHTML = '<div class="empty">请输入搜索关键词</div>';
        return;
    }

    resultPanel.innerHTML = '<div class="loading">正在搜索...</div>';
    try {
        const res = await fetch(`/api/products/search?q=${encodeURIComponent(q)}`);
        if (!res.ok) {
            throw new Error('请求失败 ' + res.status);
        }
        const data = await res.json();
        if (!Array.isArray(data) || data.length === 0) {
            resultPanel.innerHTML = '<div class="empty">没有找到相关商品</div>';
            return;
        }
        const html = data.map(item => {
            const name = item.name || '-';
            const category = item.category || '-';
            const price = (item.price != null) ? `¥${item.price}` : '-';
            const color = item.color || '-';
            const size = item.size || '-';
            const brand = item.attributes && item.attributes.brand ? item.attributes.brand : '-';
            const rating = item.rating != null ? item.rating : '-';
            return `
        <div class="card">
          <div class="card-title">${name}</div>
          <div class="card-sub">类别：${category} · 品牌：${brand}</div>
          <div class="card-meta">
            <span>价格：${price}</span>
            <span>颜色：${color}</span>
            <span>尺码：${size}</span>
            <span>评分：${rating}</span>
          </div>
        </div>
      `;
        }).join('');
        resultPanel.innerHTML = html;
    } catch (e) {
        resultPanel.innerHTML = `<div class="error">搜索失败：${e.message}</div>`;
    }
}